import java.awt.Point;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.ArrayList;


public class Arrow {
	private GridPanel parent;

	private Element startElement,endElement;
	private ArrowSegment firstSegment,lastSegment;
	public Arrow(Element startElement, GridPanel parent){
		lastSegment=new ArrowSegment(new Point(startElement.getCenterX(),startElement.getCenterY()),startElement,parent,this);
		lastSegment.setStartPoint(new Point(startElement.getCenterX(),startElement.getCenterY()));
		firstSegment=lastSegment;
		this.parent=parent;
		this.startElement=startElement;
		
	}
	
	public void moveEndPoint(Point endPoint){
		lastSegment.setEndPoint(endPoint);
		lastSegment.setEndElement(null);
		
	}
	
	public void addVertex(){
		ArrowSegment prevSegment=lastSegment.getPrevSegment();
		if(prevSegment!=null&&prevSegment.isSecondPartHorizontal()==lastSegment.isFirstPartHorizontal()){
			prevSegment.setEndPoint(lastSegment.getEndPoint());
			deleteVertex();
		}
		ArrowSegment segment=new ArrowSegment(lastSegment.getEndPoint(),null,parent,this);
		segment.setPrevSegment(lastSegment);
		lastSegment.setNextSegment(segment);
		lastSegment.setFinished(true);
		lastSegment=segment;
	}
	
	public void deleteVertex(){
		lastSegment.remove();
		lastSegment=lastSegment.getPrevSegment();
		parent.repaint();
		if(lastSegment==null)
			cancel();
		else
			lastSegment.setFinished(false);
	}
	
	public void finish(Element endElement){
		if(endElement!=startElement){
			this.endElement=endElement;
			lastSegment.setDrawArrow(true,!endElement.canAddInput());
			lastSegment.setEndElement(endElement);
			lastSegment.setFinished(true);
			endElement.addInput();
			startElement.addOutput();
		}
	}
	
	public void cancel(){
		while (lastSegment!=null){
			lastSegment.remove();
			lastSegment=lastSegment.getPrevSegment();
		}
		parent.repaint();
		parent.cancelArrow();
	}
	
	public void removeEndElement(){
		endElement=null;
		lastSegment.setDrawArrow(false,false);
	}
}
